package me.zhengjie.modules.web.service.pay.cancel;

import me.zhengjie.config.exception.WeChatException;
import me.zhengjie.constant.ConstantUtils;
import me.zhengjie.modules.system.domain.CourseOrder;
import me.zhengjie.modules.system.service.CourseOrderService;
import me.zhengjie.modules.web.domain.order.OrderCancelRequest;
import me.zhengjie.modules.web.enums.OrderStatusEnum;
import me.zhengjie.modules.web.service.pay.IOrderCancelService;
import me.zhengjie.request.ATMRContext;
import me.zhengjie.utils.enums.OrderTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Objects;

@Service
public class CourseOrderCancelServiceImpl implements IOrderCancelService {
    @Autowired
    private CourseOrderService orderService;

    @Override
    public int orderType() {
        return OrderTypeEnum.Course.getOrderType();
    }

    @Override
    public boolean execute(OrderCancelRequest request) {
        CourseOrder courderOrder = orderService.findOne(request.getOrderSn());
        if (Objects.isNull(courderOrder)){
            throw new WeChatException("参数有误");
        }
        if (courderOrder.getPayStatus().equals(ConstantUtils.Order_Payed)){
            throw new WeChatException("已支付不能取消");
        }
        if (!courderOrder.getOpenId().equals(ATMRContext.getContext().getOpenId())){
            throw new WeChatException("非法请求");
        }
        courderOrder.setOpenId(ATMRContext.getContext().getOpenId());
        courderOrder.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
        courderOrder.setOrderStatus(OrderStatusEnum.Cancel.getOrderStatus());
        orderService.update(courderOrder);
        return true;
    }
}
